﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using ProcessBase.Models;
using SubstrateHelper.Models;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Xml;
using Microsoft.Extensions.DependencyInjection;
using SubstrateHelper.Data;



namespace SubstrateHelper.Helpers
{
    public class NCHelper
    {
        //public static string RuKu1(Order order, string LotNo, double quantity, DateTime startTime, DateTime? endTime = null)
        //{
        //    string xmlPath, templatePath, xml;
        //    List<XmlModifyTemplate> templates;
        //    string addrToPost;
        //    string returnXml;


        //    string messageReturn, pkReturn;
        //    bool successReturn;

        //    //完工报告
        //    //
        //    order.UsedWanGongBaoGaoRowNo += 10;//行号增加
        //    DateTime _endTime = endTime ?? DateTime.Now;//完工时间
        //    string guid = Guid.NewGuid().ToString().Substring(0, 5);
        //    string id = $"HX-MES-{DateTime.Now.Year:0000}{DateTime.Now.Month:00}{guid}";

        //    var wangongValue = new ProcessBase.Models.WanGongBaoGaoValue()
        //    {
        //        id = id,//	
        //        dbilldate = DateTime.Now.ToString("yyyy-MM-dd"),//	
        //        dmakedate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),//	
        //        creationtime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),//	
        //        vbrowno = order.UsedWanGongBaoGaoRowNo.ToString(),//	
        //        tbstarttime = startTime.ToString("yyyy-MM-dd hh:mm:ss"),//	
        //        tbendtime = _endTime.ToString("yyyy-MM-dd hh:mm:ss"),//	
        //        vbinbatchcode = LotNo,//	
        //        nbwrnum = quantity.ToString(),//	
        //        nbwrastnum = quantity.ToString(),//	
        //        vbnote = "",//	
        //    };

        //    xmlPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Templates\\完工报告.xml");
        //    templatePath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Templates\\XmlModifyTemplate.xlsx");
        //    templates = ExcelHelper.ExcelToData.GetData<XmlModifyTemplate>(templatePath, "完工报告", "备注");
        //    xml = Helpers.XmlHelper.ModifyXml(xmlPath, templates, order, wangongValue);

        //    addrToPost = Global.Configuration.GetConnectionString("NCRuKuAddress");
        //    returnXml = Helpers.HttpHelper.Post(addrToPost, xml, true);

        //    GetResult(returnXml, out successReturn, out messageReturn, out pkReturn);

        //    if (successReturn)
        //    {
        //        //入库单
        //        guid = Guid.NewGuid().ToString().Substring(0, 5);
        //        id = $"HX-INV-{DateTime.Now.Year:0000}{DateTime.Now.Month:00}{guid}";
        //        var rukuValue = new ProcessBase.Models.RuKuDanValue()
        //        {
        //            id = id,//	表单ID
        //            dbilldate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),//	单据日期
        //            ntotalnum = quantity.ToString(),//	总数量
        //            creationtime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),//	制单时间
        //            crowno = order.UsedWanGongBaoGaoRowNo.ToString(),//	行号
        //            vfree1 = LotNo,//由于入库单的批号必须是订单上的批号，因此在此存储入库批号，以防万一
        //            nshouldnum = quantity.ToString(),//	应收主数量
        //            nshouldassistnum = quantity.ToString(),//	应收数量
        //            nnum = quantity.ToString(),//	实收主数量
        //            nassistnum = quantity.ToString(),//	实收数量
        //            dbizdate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),//	入库日期
        //            ncountnum = "1",//	箱数
        //            dproducedate = startTime.ToString("yyyy-MM-dd"),
        //            dvalidate = new DateTime(startTime.Year+5,startTime.Month,startTime.Day).ToString("yyyy-MM-dd"),
        //        };


        //        var wrs = Helpers.OracleDbHelper.GetData<V_MES_HX_WR>($"select * from V_MES_HX_WR where PK_WR = '{pkReturn}'");
        //        var wr = wrs.FirstOrDefault();
        //        xmlPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Templates\\入库单.xml");
        //        //templatePath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Templates\\XmlModifyTemplate.xlsx");
        //        templates = ExcelHelper.ExcelToData.GetData<XmlModifyTemplate>(templatePath, "入库单", "备注");
        //        xml = Helpers.XmlHelper.ModifyXml(xmlPath, templates, order, rukuValue, wr);

        //        //addrToPost = Global.Configuration.GetConnectionString("NCRuKuAddress");
        //        returnXml = Helpers.HttpHelper.Post(addrToPost, xml, true);

        //        GetResult(returnXml, out successReturn, out messageReturn, out pkReturn);
        //        if (!successReturn)
        //        {
        //            return messageReturn;
        //        }
        //    }
        //    else
        //    {
        //        return messageReturn;
        //    }


        //    //order完成数量
        //    order.QuantityDone += quantity;

        //    //order写回数据库
        //    using (var scope = Global.Host.Services.CreateScope())
        //    {
        //        var services = scope.ServiceProvider;
        //        try
        //        {
        //            var Db = services.GetRequiredService<SubstrateHelperDbContext>();
        //            Db.Orders.Update(order);
        //            Db.SaveChanges();
        //            //
        //            return null;
        //        }
        //        catch (Exception ex)
        //        {
        //            return ex.Message;
        //        }
        //    }
        //}

        public static async Task<string> RuKu(Order order, string LotNo, double quantity, DateTime startTime, DateTime? endTime = null)
        {
            string xmlPath, templatePath, xml;
            List<XmlModifyTemplate> templates;
            string addrToPost;
            string returnXml;


            string messageReturn, pkReturn;
            bool successReturn;


            if (string.IsNullOrWhiteSpace(order.WanGongBaoGaoID))
            {
                //完工报告
                //
                order.UsedWanGongBaoGaoRowNo += 10;//行号增加
                DateTime _endTime = endTime ?? DateTime.Now;//完工时间
                string guid = Guid.NewGuid().ToString().Substring(0, 5);
                string id = $"HX-MES-{DateTime.Now.Year:0000}{DateTime.Now.Month:00}{guid}";

                var wangongValue = new ProcessBase.Models.WanGongBaoGaoValue()
                {
                    id = id,//	
                    dbilldate = DateTime.Now.ToString("yyyy-MM-dd"),//	
                    dmakedate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),//	
                    creationtime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),//	
                    vbrowno = order.UsedWanGongBaoGaoRowNo.ToString(),//	
                    tbstarttime = startTime.ToString("yyyy-MM-dd hh:mm:ss"),//	
                    tbendtime = _endTime.ToString("yyyy-MM-dd hh:mm:ss"),//	
                    vbinbatchcode = LotNo,//	
                    nbwrnum = quantity.ToString(),//	
                    nbwrastnum = quantity.ToString(),//	
                    vbnote = "",//	
                };

                xmlPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Templates\\完工报告.xml");
                templatePath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Templates\\XmlModifyTemplate.xlsx");
                templates = ExcelHelper.ExcelToData.GetData<XmlModifyTemplate>(templatePath, "完工报告", "备注");
                xml = Helpers.XmlHelper.ModifyXml(xmlPath, templates, order, wangongValue);

                addrToPost = Global.Configuration.GetConnectionString("NCRuKuAddress");
                returnXml = Helpers.HttpHelper.Post(addrToPost, xml, true);

                GetWanGongResult(returnXml, out successReturn, out messageReturn, out pkReturn);
                if (successReturn)
                {
                    order.WanGongBaoGaoID = pkReturn;
                }
                else
                {
                    return messageReturn;
                }
            }




            //入库
            RuKuValue ruKuValue = new RuKuValue()
            {
                nnum = quantity,
                vnote = LotNo
            };
            RuKuValue[] values = new RuKuValue[] { ruKuValue };
            var jsonValue = Newtonsoft.Json.JsonConvert.SerializeObject(values);

            NCWebService.MesHegerukuServicePortTypeClient client = new NCWebService.MesHegerukuServicePortTypeClient();
            //var re=await client.prodInAsync("1001X0100000004DX3B0", jsonValue);
            var re = await client.prodInAsync(order.WanGongBaoGaoID, jsonValue);
            var rukuReturn = Newtonsoft.Json.JsonConvert.DeserializeObject<RuKuReturn>(re.@return);
            if (rukuReturn.code < 0)//不成功
            {
                return rukuReturn.message;
            }



            //order完成数量
            order.QuantityDone += quantity;

            //order写回数据库
            using (var scope = Global.Host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var Db = services.GetRequiredService<SubstrateHelperDbContext>();
                    Db.Orders.Update(order);
                    Db.SaveChanges();
                    //
                    return null;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
        }


        public static void GetWanGongResult(string xmlReturn, out bool success, out string message, out string pk_wr)
        {

            var doc = XDocument.Parse(xmlReturn);

            var ufinterface = doc.XPathSelectElement("/ufinterface");
            success = ufinterface.Attribute(XName.Get("successful")).Value.ToUpper() == "Y";
            message = doc.XPathSelectElement("/ufinterface/sendresult/resultdescription").Value;
            pk_wr = doc.XPathSelectElement("/ufinterface/sendresult/content").Value;

        }

        public static string WriteMesFlag(V_MES_HX_MO mo)
        {
            //string json = $"{{\"cpmohid\":\"{mo.cpmohid}\",\"cmoid\":\"{mo.cmoid}\"}}";
            //string json = $"{{cpmohid:{mo.cpmohid},cmoid:{mo.cmoid}}}";
            string json = $"cpmohid={mo.cpmohid}&cmoid={mo.cmoid}";
            string addr = Global.Configuration.GetConnectionString("MesFlagWritebackAddress");
            var ret = Helpers.HttpHelper.Post(addr, json);
            return ret;
        }


        public static string OutputToNC(IEnumerable<SubstrateInfo> substrates)
        {
            using (var scope = Global.Host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var Db = services.GetRequiredService<SubstrateHelperDbContext>();
                var trans = Db.Database.BeginTransaction();
                try
                {

                    //获得镀金基板批号
                    var lotNos = substrates.Where(x => x.OutputToNC == false).Select(x => x.LotNo).Distinct();
                    if (lotNos == null || lotNos.Count() <= 0)
                    {
                        throw new Exception("找不到基板对应的主批号。无法入库。");
                    }

                    foreach (var lotNo in lotNos)
                    {
                        var order = Helpers.LotNoHelper.GetOrderFromOutputLotNo(lotNo);
                        var toOutput = substrates.Where(x => x.LotNo == lotNo && x.OutputToNC == false);
                        int quantity = toOutput.Count();

                        var re = Helpers.NCHelper.RuKu(order, lotNo, quantity, order.OrderBillDate);
                        if (string.IsNullOrEmpty(re.Result))//成功
                        {
                            foreach (var sub in toOutput)
                            {
                                sub.OutputToNC = true;
                                Db.SubstrateInfos.Update(sub);
                            }
                        }
                        else
                        {
                            trans.Rollback();
                            return re.Result;
                        }


                    }

                    Db.SaveChanges();
                    trans.Commit();
                    //
                    return null;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return ex.Message;
                }
            }

           
        }
    }
}
